import type { ApiCommonTypes } from "@/api/api-types/api-common-types";
import { COS_TYPE } from "../enum/pd-enum";
import COS from 'cos-wx-sdk-v5';
import PD from "../libs";
//桶配置
const bucketConfig = {
	[COS_TYPE.business]: {
		Bucket: 'business-1300661617',
		Region: 'ap-shanghai',
		BucketName: 'business',
		Fold: (filepath) => {//业务类目录根据资源类型动态计算
			return getTypesByPath(filepath);
		},
	},
	[COS_TYPE.driverAuthFiles]: {
		Bucket: 'audit-file-1300661617',
		BucketName: 'auditFile',
		Region: 'ap-shanghai',
		Fold: 'driver'
	},
	[COS_TYPE.recroderd]: {
		Bucket: 'voices-1300661617',
		BucketName: 'voice',
		Region: 'ap-shanghai',
		Fold: 'driver'
	},
};

//允许上传的图片类型
const imgTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'tiff', 'psd',];

//允许上传的音频类型
const audioTypes = ['mp3', 'mp4', 'ogg', 'wav', 'webm'];

//允许上传的视频类型
const videoTypes = [
	'webm', 'mkv', 'mp4', 'ogv', 'ogg', 'avi', 'flv', 'f4v', 'm4v', 'mov', 'divx',
	'xvid', 'rm', 'rmvb', 'wmv', 'asf', 'asx', 'ts', 'm2ts', 'm2t', 'mts', 'mjpeg',
	'mjpg', 'mpg', 'mp2', 'mpeg', 'mpv', 'mpg', 'mpeg', 'mpe', 'mpv2', 'svi', '3gp',
	'3g2', 'mxf', 'la', 'dv', 'mxf', 'f4p', 'f4a', 'f4b'
];

/**
 * 根据文件名，返回文件的类型，如果最终存入business桶， 该类型将作为在桶里的目录使用
 * @param {string} filePath 
 * @returns {string} "video" | "img" | "audio" | "other"
 */

const getTypesByPath = (filePath: string) => {
	if (!filePath) throw new Error('getTypesByPath缺乏必要参数');
	if (typeof filePath !== 'string') throw new Error('getTypesByPath参数类型错误');
	const ext = PD.Tool.getExtByFileName(filePath);
	if (imgTypes.includes(ext)) return 'img';
	if (audioTypes.includes(ext)) return 'audio';
	if (videoTypes.includes(ext)) return 'video';
	return 'other';
};


type CosAuthCallBackParams = {
	TmpSecretId: string,
	TmpSecretKey: string,
	XCosSecurityToken: string,
	StartTime: number,
	ExpiredTime: number
};

export default class PdCos {
	public cosType: COS_TYPE;
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	public cos: any;
	public bucketConfig: typeof bucketConfig[keyof typeof bucketConfig];//当前桶配置
	private file_list : string[] = [];//服务端下发的文件名

	constructor(type: COS_TYPE, authConfig: ApiCommonTypes.GetCosAuthRes) {
		this.cosType = type;
		this.bucketConfig = bucketConfig[this.cosType];
		this.file_list = authConfig.file_list;
		this.cos = this.createIns(authConfig);
	}

	private createIns(authConfig: ApiCommonTypes.GetCosAuthRes) {
		return new COS({
			getAuthorization: (_, callback: (p: CosAuthCallBackParams) => void) => {
				callback({
					TmpSecretId: authConfig.secret_id,
					TmpSecretKey: authConfig.secret_key,
					XCosSecurityToken: authConfig.session_token,
					StartTime: authConfig.start_time,
					ExpiredTime: authConfig.expired_time
				});
			}
		});
	}

	public upload(filePath: string) : Promise<{cosUrl : string}> {
		if (!filePath) throw new Error(`cos->upload：缺乏必要参数：filepath`);
		return new Promise((r, j) => {
			this.cos.postObject({
				Bucket: this.bucketConfig.Bucket,
				Region: this.bucketConfig.Region,
				Key: `${this.file_list[0]}.${PD.Tool.getExtByFileName(filePath)}`,
				FilePath: filePath,
			}, (err, data) => {
				err && j(err);
				data && r({
					cosUrl: `https://${data.Location}`
				});
			});
		});
	}
}